#include "Grammar.h"
#include "Code.h"
#include <stdarg.h>
#include <stack>
#include <exception>

using namespace std;;

CGrammar::CGrammar()
{
	LOG("Initialize Grammar");
	m_pScannerRule = CScannerRule::create();
	m_pScanner = CScanner::create(m_pScannerRule);
	m_pParser = CParser::create(m_pScanner);
    
    CTokenManager::Instance()->SetScannerRule(m_pScannerRule);
}


CGrammar::~CGrammar()
{
	LOG("Destroying Grammar");

}

/*
*	@method preInterprete
*	@description PreInterprete
*	@return void
*/
void CGrammar::preInterprete()
{
	// init the scope for the parser
	this->enterScope();
}

/*
*	@method interprete
*	@description interprete
*	@param std::istream& is the stream of code
*	@return void
*/
void CGrammar::interprete( std::istream& is )
{
	this->preInterprete();

	m_pParser->Parse(is);

	this->postInterprete();
}

/*
*	@method postInterprete
*	@description postInterprete
*	@return void
*/
void CGrammar::postInterprete()
{
	// clear the scope
	this->m_pScope = CScopePtr();
}


CScannerRulePtr CGrammar::GetScannerRule()
{
	return m_pScannerRule;
}

CScannerPtr CGrammar::GetScanner()
{
	return m_pScanner;
}

CParserPtr CGrammar::GetParser()
{
	return m_pParser;
}



/*
*	@method enterScope
*	@description Enter a new scope
*	@return CScopePtr the pointer to the new scope
*/
CScopePtr CGrammar::enterScope()
{
	return m_pScope = CScope::create(m_pScope);
}

/*
*	@method enterScope
*	@description Enter a new scope
*	@param CScopePtr pNewScope the pointer to the new scope
*	@return CScopePtr the pointer to the new scope
*/
CScopePtr CGrammar::enterScope( CScopePtr pNewScope )
{
	pNewScope->setParentScope(m_pScope);
	return m_pScope = pNewScope;
}

/*
*	@method leaveScope
*	@description Leave current scope
*	@return CScopePtr the pointer to the parent scope
*/
CScopePtr CGrammar::leaveScope()
{
	return m_pScope = m_pScope->getParentScope();
}

/*
*	@method getScope
*	@description Get the current scope pointer
*	@return CScopePtr the pointer to the current scope
*/
CScopePtr CGrammar::getScope()
{
	return m_pScope;
}

